package com.dapeis.web.wx.controller.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.core.base.Pager;
import com.ag.core.exception.InvalidParamException;
import com.ag.core.exception.SysTipsException;
import com.ag.core.utils.AgAssert;
import com.ag.utils.NumberUtils;
import com.ag.utils.json.AGsonBuilder;
import com.ag.utils.json.GsonUtils;
import com.dapeis.core.convert.pager.PlanPagerSearchConvertCriteria;
import com.dapeis.core.utils.DBConfigUtils;
import com.dapeis.core.utils.StringUtil;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Plan;
import com.dapeis.domain.Order;
import com.dapeis.domain.ext.CollocationExt;
import com.dapeis.domain.ext.OrderExt;
import com.dapeis.pay.swiftpass.util.SPPayUtil;
import com.dapeis.service.CollocationPlanService;
import com.dapeis.service.CollocationService;
import com.dapeis.service.CommentService;
import com.dapeis.service.OrderService;
import com.dapeis.service.ShopService;
import com.dapeis.service.TIMService;
import com.dapeis.web.wx.controller.IPlanController;
import com.dapeis.web.wx.controller.RestController;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * @author 作者 E-mail: hzyuanyong@126.com
 * @version 创建时间：2017年5月22日 上午10:36:59 时尚圈
 */
@Controller
@RequestMapping(value = "/wx/fashion")
public class PlanController extends RestController implements IPlanController {
    @Resource
    CollocationPlanService planService;
    @Resource
    OrderService orderService;
    @Resource
    CollocationService collocationService;
    @Resource
    CommentService commentService;
    @Resource
    TIMService timService;
    @Resource
    ShopService shopService;

    @Override
    public JsonElement all(
	    @RequestParam(required = false) Integer currentPager,
	    HttpServletRequest request) {
	Pager pager = new Pager();
	pager.init(OrderExt.class, new PlanPagerSearchConvertCriteria());
	Example example = new Example(Plan.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Plan.PROPERTY_STATE, StylistConstants.State.NORMAL);
	criteria.andEqualTo(Plan.PROPERTY_ISSUE,
		StylistConstants.PlanState.ISSUE);
	example.orderBy(Plan.PROPERYT_ID).desc();
	pager.setExample(example);
	if (NumberUtils.isValid(currentPager)) {
	    pager.setCurrentPage(currentPager);
	}
	planService.pager(pager);
	if (!pager.getItemList().isEmpty()) {
	    List<Plan> list = pager.getItemList();
	    for (Iterator iterator = pager.getItemList().iterator(); iterator
		    .hasNext();) {
		Plan plan = (Plan) iterator.next();
		if (null != plan) {
		    if (planService.isExitAgree(plan, getThreadLocalUserId())) {
			plan.setAgreeValue(StylistConstants.Agree.YES);
		    }
		}
	    }
	}
	JsonObject json = success();
	json.add("pager", AGsonBuilder.create().toJsonTree(pager));
	return json;

    }

    @Override
    public JsonElement detail(@RequestParam Integer planId,
	    HttpServletRequest request) {
	Plan plan = planService.selectByPrimaryKey(planId);
	AgAssert.notNull(plan, SysTipsException.class, "查询不到方案信息ID：" + planId);
	CollocationExt collocationExt = collocationService
		.getCollocationExtMapper().selectByPrimaryKey(
			plan.getCollocationId());
	if (planService.isExitAgree(plan, getThreadLocalUserId()))
	    plan.setAgreeValue(StylistConstants.Agree.YES);
	JsonObject json = success();
	json.add("collocation", AGsonBuilder.create()
		.toJsonTree(collocationExt));
	json.add("plan", AGsonBuilder.create().toJsonTree(plan));
	return json;
    }

    /**
     * 点赞
     */
    @Override
    public JsonElement agree(@RequestParam Integer planId,
	    HttpServletRequest request) {
	Plan plan = planService.selectByPrimaryKey(planId);
	AgAssert.notNull(plan, SysTipsException.class, "查询不到方案信息:" + planId);
	planService.doAgree(plan, getThreadLocalUserId());
	JsonObject json = success();
	return json;
    }

    /**
     * 打赏
     */
    @Override
    public JsonElement award(@RequestParam Integer planId, String money,
	    HttpServletRequest request) {
	Plan plan = planService.selectByPrimaryKey(planId);
	AgAssert.notNull(plan, SysTipsException.class, "查询不到方案信息:" + planId);
	AgAssert.notNull(money, SysTipsException.class, "money为空!");
	// money String 类型 0.01
	Float priceFooat = null;
	try {
	    Float moneyFloat = new Float(money);
	    priceFooat = new Float(moneyFloat * 100);
	} catch (Exception e) {
	    throw new InvalidParamException("打赏金额非法!");
	}
	String pay_info = "";
	Order dbOrder = orderService.getPlanOrder(planId,
		getThreadLocalUserId());
	if (null != dbOrder) {
	    orderService.closeSwfitOrder(dbOrder);
	}
	Order order = orderService.createOrderPlan(plan,
		getThreadLocalUserId(), priceFooat.intValue());
	Map resultMap = orderService.createUnified(request, order,
		getThreadLocalUser());
	if (SPPayUtil.checkResut(resultMap)) {// 成功
	    pay_info = resultMap.get("pay_info").toString();
	    order.setUnifiedTime(new Date().getTime() / 1000);
	    order.setPayInfoExt(pay_info);
	    orderService.updateByPrimaryKeySelective(order);
	} else {
	    throw new InvalidParamException(SPPayUtil.getResultMsg(resultMap));
	}
	JsonObject json = success();
	json.add("payInfo", GsonUtils.parse(pay_info));
	// json.addProperty("price", getPrice(order.getOriginalPrice()));
	json.addProperty("token", resultMap.get("token_id").toString());
	return json;

    }

    /**
     * 搭配师主页
     */
    @Override
    public JsonElement collocation(@PathVariable Integer collocationId,
	    HttpServletRequest request) {
	CollocationExt collocationExt = collocationService
		.getCollocationExtMapper().selectByPrimaryKey(collocationId);
	AgAssert.notNull(collocationExt, SysTipsException.class, "搭配师信息不存在id:"
		+ collocationId);
	// boolean isFriend = timService.checkFriend(collocationId,
	// getThreadLocalUserId());
	JsonObject json = success();
	json.add("collocation", AGsonBuilder.create()
		.toJsonTree(collocationExt));
	json.add(
		"plans",
		AGsonBuilder.create().toJsonTree(
			planService.getPlanImgList(collocationId)));
	json.add(
		"shops",
		AGsonBuilder.create().toJsonTree(
			shopService.getShopByCollocationId(collocationId)));
	return json;
    }

    public String getPrice(Integer price) {
	DecimalFormat decimalFormat = new DecimalFormat("0.00");
	Float priceFloat = new Float(price);
	String pasStr = decimalFormat.format(priceFloat / 100);
	// System.out.println(pasStr);
	return pasStr;
    }

}
